﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InductBase;
using SharpBolt.BasicIntefaces;
using SharpBolt.Graphics.GraphicInstances;

namespace SharpBolt.Graphics.Particles
{
    public class ParticleEmitter : IDropable
    {
        
        public ParticleSystem ParticleSystem;
        public ParticleScheme Scheme { get; set; }
        public ParticleContainer Container;

        public bool OverrideDensity { get; set; }
        public double Density { get; set; }
        public double PerSecond { get; set; }

        public Rec Area { get; set; }

        public bool Emitts { get; set; }
        public bool Frozen { get; set; }
        public bool Enabled { get; set; }

        public ParticleEmitter()
        {
            Container = new ParticleContainer();
            Area = new Rec(0, 0, 16, 16);
            Density = 0;
            PerSecond = 2;
            Emitts = true;
            Frozen = false;
            Enabled = true;
            Scheme = null;
        }

        double lastTimePS;
        double lastTimeD;

        public void Update(double delta)
        {
            if (Emitts)
            EmittParticles(delta);
            Container.UpdateParticles(delta);
        }
              
        private void EmittParticles(double delta)
        {
            if (Scheme == null) return;

            int number = 0;

            double perSecond = Scheme.PerSecond;
            if (OverrideDensity) perSecond = PerSecond;

            if (perSecond > 0)
            {
                double intervalPS = 1000.0 / perSecond;

                if (intervalPS > 0)
                {
                    int numberPS = (int)(lastTimePS / intervalPS);
                    lastTimePS = lastTimePS % intervalPS;
                    lastTimePS += delta;
                    number += numberPS;
                }
            }

            double density = Scheme.Density;
            if (OverrideDensity) density = Density;


            if (density > 0)
            {
                int numberD = (int)(lastTimeD / 1000.0 * density * Area.Area);
                if (numberD < 1)
                    lastTimeD += delta;
                else
                    lastTimeD = 0;

                number += numberD;
            }

            if (number > Scheme.MaxParticlesNumber)
                number = Scheme.MaxParticlesNumber;

            Container.Burst(number, Scheme, Area);            
        }       
        public void Draw(Painter painter)
        {
            Container.Draw(painter);
        }

        public bool IsDropped { get; set; }
        public void Drop()
        {
            ParticleSystem.RemoveEmitter(this);
        }

    }
}
